<?php

include('header.php');
include('month_opt.php');
include('day_opt.php');
include('year_opt.php');
include('state_opt.php');
require_once('class/recaptchalib.php');

$publickey = "6Le2w8cSAAAAAAhVbxDkH8Oe6Sq1YZ3fzVH4gGUD"; // you got this from the signup page
$recaptcha = recaptcha_get_html($publickey);
$smarty->assign('recaptcha', $recaptcha);

//if is postback
if (isset($_POST['Submit'])) {
    $error = array();
    setcookie('postback', 'yes', time() + 300, "/");
    //check post variables for required fields
    if (isset($_POST['ime']) && !empty($_POST['ime']) &&
            isset($_POST['username']) && !empty($_POST['username']) &&
            isset($_POST['password']) && !empty($_POST['password']) &&
            isset($_POST['password_repeat']) && !empty($_POST['password_repeat']) &&
            isset($_POST['grad']) && !empty($_POST['grad']) &&
            isset($_POST['drzava']) && !empty($_POST['drzava']) &&
            isset($_POST['email']) && !empty($_POST['email'])) {

        $user['datum_reg'] = date("d m Y");
        $user['ime'] = mres($_POST['ime']);
        $user['username'] = mres($_POST['username']);
        $user['password'] = $_POST['password'];
        $user['password_repeat'] = $_POST['password_repeat'];
        $user['email'] = mres($_POST['email']);
        $user['mesec_datum_rodjenja'] = mres($_POST['mesec_datum_rodjenja']);
        $user['dan_datum_rodjenja'] = mres($_POST['dan_datum_rodjenja']);
        $user['godina_datum_rodjenja'] = mres($_POST['godina_datum_rodjenja']);
        $user['datum_rodj'] = $user['mesec_datum_rodjenja'] + '/' + $user['dan_datum_rodjenja'] + '/' + $user['godina_datum_rodjenja'];
        $user['grad'] = mres($_POST['grad']);
        $user['drzava'] = mres($_POST['drzava']);
        $user['telefon'] = mres($_POST['telefon']);
        $user['www'] = mres($_POST['www']);
        $user['studio'] = mres($_POST['studio']);
        $user['adresa_studija'] = mres($_POST['adresa_studija']);
        $user['telefon_studio'] = mres($_POST['telefon_studio']);
        $user['email_studio'] = mres($_POST['email_studio']);
        $user['www_studio'] = mres($_POST['www_studio']);
        $user['osebi'] = mres($_POST['osebi']);
        $user['prikaz_email'] = isset($_POST['prikaz_email']) ? 1 : 0;
        $user['prikaz_telefon'] = isset($_POST['prikaz_telefon']) ? 1 : 0;

        //set cookies for populating input fields if registration failed
        foreach ($user as $key => $value) {
            if ( !in_array($key, array('password', 'password_repeat', 'datum_rodj'))) {
                if(isset($value) && !empty ($value)) {
                setcookie($key, $value, time() + 300, "/");
                }
            }
        }

        //check username exist
        if (checkIfUsernameExist($user['username'])) {
            array_push($error, 'Korisničko ime koje ste uneli već postoji!');
        }

        //check email exist
        if (checkIfEmailExist($user['email'])) {
            array_push($error, 'Email koji ste uneli već postoji!');
        }

        //check check If Just Register With Session
        if (!empty($_SESSION['just_registered']) || empty($user_info['is_guest'])) {
            array_push($error, 'Već ste se jednom registrovali!');
        }

        //check if passwords are matched
        if ($user['password'] != $user['password_repeat']) {
            array_push($error, 'Unete šifre se ne poklapaju!');
        }

        //check captcha
        if (!isset($_POST['recaptcha_response_field']) || empty($_POST['recaptcha_response_field'])) {
            array_push($error, 'Unesite reči sa slike!');
        } else {
            $response = mres($_POST['recaptcha_response_field']);
            //hack for smf
            unset($_POST['recaptcha_response_field']);
            $chalenge = mres($_POST['recaptcha_challenge_field']);
            //hack for smf
            unset($_POST['recaptcha_challenge_field']);
            if (!validCaptcha($chalenge, $response)) {
                array_push($error, 'Niste uneli ispravno reči sa slike!');
            }
        }

        //if it is all OK
        if (empty($error)) {
            //do smf registration
            require_once($sourcedir . '/Subs-Members.php');
            if (!isset($_SESSION['old_url'])) {
                $_SESSION['old_url'] = $_SERVER['HTTP_REFERER'];
            }
            $regOptions = array(
                'interface' => 'guest',
                'username' => $user['username'],
                'email' => $user['email'],
                'password' => $user['password'],
                'password_check' => $user['password_repeat'],
                'openid' => '',
                'auth_method' => '',
                'check_reserved_name' => true,
                'check_password_strength' => true,
                'check_email_ban' => true,
                'send_welcome_email' => !empty($modSettings['send_welcomeEmail']),
                'require' => !empty($modSettings['coppaAge']) && !$verifiedOpenID && empty($_SESSION['skip_coppa']) ? 'coppa' : (empty($modSettings['registration_method']) ? 'nothing' : ($modSettings['registration_method'] == 1 ? 'activation' : 'approval')),
                'extra_register_vars' => array(),
                'theme_vars' => array(),
            );
            $smf_member_id = registerMember($regOptions);

            //do portal registration
            if (!empty($smf_member_id)) {
                $user['password'] = md5($user['password']);
                if (portalDbRegister($user)) {
                    //registration success
                    //if image is selected for upload do upload                   
                    if (isset($_FILES["file"]["name"]) && !empty($_FILES["file"]["name"])) {
                        $uploadReturn = doUpload($user['username']);
                        if ($uploadReturn == '') {
                            //upload success - everything else done fine
                            $smarty->display('registracija_kraj.tpl');
                        } else {
                            //upload failed - display why
                            $smarty->display('registracija_kraj.tpl');
                            echo '<p>Upload slike za profil nije prošao. ' + $uploadReturn + '</p>';
                        }
                    } else {
                        //everything done fine and we don't have profile picture to upload
                        $smarty->display('registracija_kraj.tpl');
                    }
                } else {
                    //registered with smf but not registered with portal
                    //remove user with id=$smf_member_id from smf
                    $deleteMsg = deleteSmfMember($smf_member_id) ? 'Korisnik je uspesno obrisan. Pokušajte ponovo da se registrujete.' : 'Korisnik neuspešno obrisan. Kontaktirajte administratora.';
                    //add error
                    array_push($error, 'Došlo je do greške prilikom registracije na portal!' + $deleteMsg);
                    $smarty->assign('errors', $error);
                    $smarty->display('registracija.tpl');
                }
            } else {
                //error during registration to smf
                //add error
                array_push($error, 'Došlo je do greške prilikom registracije na forum! Kontaktirajte administratora.');
                $smarty->assign('errors', $error);
                $smarty->display('registracija.tpl');
            }
        } else {
            //display registracija.tpl and assign error
            $smarty->assign('errors', $error);
            $smarty->display('registracija.tpl');
        }
        //not filled all required fields
    } else {
        array_push($error, 'Popunite sva neophodna polja');
        $smarty->assign('errors', $error);
        $smarty->display('registracija.tpl');
    }
    //not postback
} else {
    $smarty->assign('errors', array());
    $smarty->display('registracija.tpl');
}




include('footer.php');

function validCaptcha($chalenge, $response) {
    $privatekey = "6Le2w8cSAAAAADezyNhaMzyUQPGgIxmxSlM7m3Rv";
    $resp = recaptcha_check_answer($privatekey,
                    $_SERVER["REMOTE_ADDR"],
                    $chalenge,
                    $response);

    if (!$resp->is_valid) {
        // What happens when the CAPTCHA was entered incorrectly
        return false;
    } else {
        // Your code here to handle a successful verification
        return true;
    }
}

function doUpload($username) {
    require_once('functions/thumb.php');
    $parent_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    //if folder not exist create it
    $imagefolder = $parent_dir . '/media/autori/' . $username . '/slike_za_profil/';
    if (!is_dir($imagefolder))
        mkdir($imagefolder, 0777, true);
    $thumbfolder = $parent_dir . '/media/autori/thumbs/' . $username . '/slike_za_profil/';
    if (!is_dir($thumbfolder))
        mkdir($thumbfolder, 0777, true);

    $uploadStatus = upload_and_create_thumb($imagefolder, $thumbfolder);
    if ($uploadStatus == "Success") {
        updateProfilPicture($_FILES["file"]["name"], $username);
        return '';
    } else {
        return $uploadStatus;
    }
}



?>
